package com.info33.platform.common.exception.handler;

import com.info33.platform.common.exception.BaseException;
import com.info33.platform.common.mvc.vo.Result;
import org.omg.CORBA.UserException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;


@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 用户异常
     */
    @ExceptionHandler(value = UserException.class)
    public ResponseEntity<Result<?>> userExceptionHandle(UserException e) {
        e.printStackTrace();
        // DataResponse failure = new DataResponse().setStatus(Status.FAILED).setMsg(e.getMsg());
        return ResponseEntity.ok().body(Result.error(10001, "用户信息异常"));
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(value = BaseException.class)
    public ResponseEntity<Result<?>> handle(BaseException e) {
        e.printStackTrace();
        // DataResponse failure = new DataResponse().setStatus(Status.FAILED).setMsg(e.getMsg());
        return ResponseEntity.ok().body(Result.error(e.getMessage()));
    }


    /* @ExceptionHandler(value = BaseException.class)
     public Result<?> errorHandler(HttpServletRequest req, BaseException e) throws Exception {
         e.printStackTrace();
         System.err.println("asdsad");
         return Result.error(e.getMessage());
     }*/
    //处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常，详情继续往下看代码
    @ExceptionHandler(BindException.class)
    public Result<?> BindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return Result.error(506, message);
    }

    //处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是javax.validation.ConstraintViolationException
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<?> constraintViolationExceptionHandler(ConstraintViolationException e) {
        //获取异常中第一个错误信息
        String message = e.getConstraintViolations().iterator().next().getMessage();
        return Result.error(507, message);
    }

    //处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常。
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<?> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        return Result.error(508, "入参不合法", e.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList()));
    }
}
